package org.magicbox.qjunTPO.controller;

import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/test")
public class TestController {
    @ResponseBody
    @Secured("ROLE_LV0")  //需要有对应角色才能访问该接口
    @RequestMapping("/LV0")
    public Result toMain1(){
        return Result.success("lv0权限");
    }


    @ResponseBody
    @Secured("ROLE_LV1")  //需要有对应角色才能访问该接口
    @RequestMapping("/LV1")
    public Result toMain2(){
        return Result.success("lv1权限");
    }

    @ResponseBody
    @Secured("ROLE_LV2")  //需要有对应角色才能访问该接口
    @RequestMapping("/LV2")
    public Result toMain3(){
        return Result.success("lv2权限");
    }

    @Secured("ROLE_LV3")  //需要有对应角色才能访问该接口
    @RequestMapping("/LV3")
    public Result toMain4(){
        return Result.success("lv3权限");
    }


    @ResponseBody
    @PreAuthorize("hasAnyAuthority('UserPower')")   //允许这两个角色访问
    @RequestMapping("/userPower")
    public Result userPower(){
        return Result.success("userPower权限");
    }



    @Autowired
    UploadService uploadService ;
    @RequestMapping(value = "/upload/img",method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        if(multipartFile.isEmpty()) return "文件错误!";
        //1.获取指定的文件夹
//        String dir = request.getParameter("dir");
        String dir = "test";
        String contentType = multipartFile.getContentType();
//        if(!contentType.equals("png|jpeg|jpg|gif")) return "文件类型错误0";
        if(!contentType.matches("\\S*\\.(jpg|png|gif|jpeg)")) return "文件类型错误";
        return uploadService.uploadImg(multipartFile,dir);

    }
}
